﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Business.Classes;
using DAL;
using System.Collections.Generic;

namespace UI
{
    public partial class manterPostNew : System.Web.UI.Page
    {
        PostNewBusiness postNewBusiness;
        Usuario user = null;
        bool ehAdministrador = false;
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                user = (Usuario)Session["user"];
                if (user == null)
                {
                    Response.Redirect(new Controlador.Controladora().GetPageLogin());
                }

                //Verifica o perfil do usuario
                if (user.PerfilUsuario.descricao == "Administrador")
                {
                    ehAdministrador = true;
                }

                if (!IsPostBack)
                {
                    fillGridView(ehAdministrador);
                }
            }
            catch (Exception)
            {
                throw;
            }
            
        }

        protected void btNew_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/editarPostNew.aspx");
        }

        protected void gvPostNew_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gvPostNew.EditIndex = e.NewEditIndex;
            fillGridView(ehAdministrador);
            Response.Redirect("~/editarPostNew.aspx?idPostNew=" + gvPostNew.DataKeys[e.NewEditIndex]["idPostNew"].ToString());
        }

        private void fillGridView(bool ehAdministrador)
        {
            postNewBusiness = new PostNewBusiness();
            if (ehAdministrador)
                gvPostNew.DataSource = postNewBusiness.getAllPostNew();
            else
                gvPostNew.DataSource = postNewBusiness.getAllPostNewByUser(user);
            gvPostNew.DataBind();
        }

        protected void gvPostNew_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            gvPostNew.EditIndex = e.RowIndex;
            fillGridView(ehAdministrador);

            PostNew postNew = postNewBusiness.getPostNewByID(Convert.ToInt32(gvPostNew.DataKeys[e.RowIndex]["idPostNew"]));

            postNewBusiness.deletePostnew(postNew);
            fillGridView(ehAdministrador);
        }
    }
}
